package models

import (
	"gorm.io/gorm"

	"golang.org/x/crypto/bcrypt"
	// "fmt"
)

type Admin struct {
	ID          int      `json:"id" gorm:"column:id;"`
	IsSuper     int      `json:"is_super_admin" gorm:"column:is_super;->;<-`
	CountyIndex int      `json:"county_index" gorm:"column:county_index;  validate:"get=0""`
	Name        string   `json:"name" gorm:"column:name;" validate:"min=1"`
	Username    string   `json:"username" gorm:"column:username;" validate:"min=6"`
	LastLoginAt JSONTime `json:"-" gorm:"column:last_login_at;"`
}

type AdminWithPasswd struct {
	Admin
	Passwd string `json:"password" gorm:"column:passwd;"`
}

// 实现 TableName 方法指定表名
func (AdminWithPasswd) TableName() string {
	return "admins"
}

func (a *AdminWithPasswd) BeforeCreate(tx *gorm.DB) (err error) {

	if len(a.Passwd) > 0 {

		// Generate hashed password
		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(a.Passwd), bcrypt.DefaultCost)
		if err != nil {
			return err
		}

		a.Passwd = string(hashedPassword)
	}

	return
}

// Verify password
func (a *AdminWithPasswd) CheckPasswd(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(a.Passwd), []byte(password))
	if err != nil {
		return false
	} else {
		return true
	}
}
